package com.hsgene.user.service.impl;

import com.hsgene.common.util.basic.JsonUtils;
import com.hsgene.common.util.basic.SimpleRegexUtils;
import com.hsgene.common.util.basic.UUID32;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.security.MD5Utils;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.common.util.validation.ObjectChecker;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.user.constants.UserIntType;
import com.hsgene.user.constants.UserType;
import com.hsgene.user.converter.UserConverter;
import com.hsgene.user.domain.GeneticTestingUser;
import com.hsgene.user.domain.ManagerAccount;
import com.hsgene.user.domain.User;
import com.hsgene.user.domain.UserClass;
import com.hsgene.user.dto.register.ManagerRegisterDto;
import com.hsgene.user.dto.register.RegisterDto;
import com.hsgene.user.dto.user.customer.CustomerDto;
import com.hsgene.user.exception.UserErrorCode;
import com.hsgene.user.persistence.GeneticTestingUserRepository;
import com.hsgene.user.persistence.ManagerRepository;
import com.hsgene.user.persistence.UserRepository;
import com.hsgene.user.service.RegisterService;
import com.hsgene.user.service.api.GeneratorService;
import com.hsgene.user.service.api.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * 用户注册ServiceImpl
 *
 * @author wangbing
 * @version 1.0, 2018/7/2
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    private final static String ID_GENERATOR_USER = "user";

    private final static String NICK_NAME_PREFIX = "yinzi";

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ManagerRepository managerRepository;

    @Resource
    private GeneratorService generatorService;

    @Resource
    private SecurityService securityService;

    @Resource
    private GeneticTestingUserRepository geneticTestingUserRepository;

    @Value("${user.avatar.default}")
    private String userDefaultAvatar;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<CustomerDto> addCustomer(RegisterDto registerInfo) {
        // 校验注册手机号
        if (!SimpleRegexUtils.isMobile(registerInfo.getPhone())) {
            return ApiResult.fail(UserErrorCode.USER_PHONE_NOT_FORMAT);
        }
        // 查询注册手机号是否已存在
        User existedUser = userRepository.findByPhone(registerInfo.getPhone());
        UserClass userClass;
        if (Objects.isNull(existedUser)) {
            // 当前用户不存在
            String userId = generatorService.getGenerator(ID_GENERATOR_USER, null).getData().getSerialNumber();
            existedUser = new User();
            existedUser.setId(userId);
            existedUser.setPhone(registerInfo.getPhone());
            existedUser.setNickName(NICK_NAME_PREFIX + existedUser.getPhone());
            userRepository.saveUser(existedUser);
        } else {
            // 查询当前手机号是否注册平台普通用户，没有则为其注册平台普通用户
            userClass = userRepository.findUserClass(existedUser.getId(), UserType.CUSTOMER.getValue());
            if (!Objects.isNull(userClass)) {
                return ApiResult.fail(UserErrorCode.USER_EXISTED);
            }
        }
        // 保存用户分类信息
        userClass = new UserClass();
        userClass.setUserId(existedUser.getId());
        userClass.setUserType(UserType.CUSTOMER.getValue());
        userClass.setAvailable(Boolean.TRUE);
        userClass.setRegisterIp(registerInfo.getRegisterIp());
        if (!ObjectChecker.isNull(registerInfo.getExtensionInfo(), true)) {
            userClass.setRegisterExtraInfo(JsonUtils.objectToJson(registerInfo.getExtensionInfo()));
        }
        userRepository.saveUserClass(userClass);
        // 注册成功
        return ApiResult.succ(UserConverter.buildCustomerDto(existedUser, userClass));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<GeneticTestingUser> registerCustomer(RegisterDto registerInfo) {
        // 校验注册手机号
        if (!SimpleRegexUtils.isMobile(registerInfo.getPhone())) {
            return ApiResult.fail(UserErrorCode.USER_PHONE_NOT_FORMAT);
        }
        GeneticTestingUser user = geneticTestingUserRepository.findByPhone(registerInfo.getPhone());
        if (user != null) {
            return ApiResult.fail(UserErrorCode.USER_EXISTED);
        }
        user = new GeneticTestingUser();
        user.setId(UUID32.randomUUIDString());
        //user.setNick(SimpleRegexUtils.hiddenMobile(registerInfo.getPhone()));
        user.setNick("YZW" + System.currentTimeMillis());
        user.setName(registerInfo.getPhone());
        user.setPhone(registerInfo.getPhone());
        user.setAvatar(userDefaultAvatar);
        user.setUserType(UserIntType.CUSTOMER.getValue());
        user.setCreateDateTime(new Date());
        user.setDefaultAvatar(userDefaultAvatar);
        geneticTestingUserRepository.saveUser(user);

        return ApiResult.succ(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<NullObject> addManager(ManagerRegisterDto registerInfo) {
        FieldChecker.checkEmpty(registerInfo, "registerInfo");
        registerInfo.check();
        // 判断添加的管理员用户类型
        UserType userType = registerInfo.getSupplierId() == 0 ? UserType.MANAGER : UserType.SUPPLIER;
        // 超级管理员
        ManagerAccount account = managerRepository.findByUserName(registerInfo.getUserName());
        if (!ObjectChecker.isNull(account, false)) {
            return ApiResult.fail(UserErrorCode.USER_NAME_EXISTED);
        }
        ApiResult<GeneratorDto> generatorResult = generatorService.getGenerator(ID_GENERATOR_USER, null);
        if (!generatorResult.isSucc()) {
            return ApiResult.fail(generatorResult.getError());
        }
        // 保存账号基本信息
        String userId = generatorResult.getData().getSerialNumber();
        Date now = new Date();
        account = new ManagerAccount();
        account.setId(userId);
        account.setUserName(registerInfo.getUserName());
        ApiResult<String> decryptResult = securityService.rsaDecrypt(registerInfo.getPassword());
        if (!decryptResult.isSucc()) {
            return ApiResult.fail(decryptResult.getError());
        }
        String decryptPassword = decryptResult.getData();
        account.setPassword(MD5Utils.getMD5Code(decryptPassword));
        account.setDeleted(false);
        account.setSupplierId(registerInfo.getSupplierId());
        account.setCreateTime(now);
        account.setUpdateTime(now);
        managerRepository.save(account);
        // 保存用户分类信息
        UserClass userClass = new UserClass();
        userClass.setUserId(userId);
        userClass.setUserType(userType.getValue());
        userClass.setAvailable(Boolean.TRUE);
        userClass.setRegisterIp(registerInfo.getRegisterIp());
        userRepository.saveUserClass(userClass);

        return ApiResult.succ();
    }
}
